/**
 * es11 matchAll
 */
const str = `
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div>1</div>
  <p>p</p>
  <span>span</span>
  <div>2div</div>
  <div>3</div>
</body>
</html>
`
// 1. exec g
function selectDiv(regExp, str) {
  let matches = []
  while(true) {
    console.log(regExp.lastIndex)
    const match = regExp.exec(str)
    if(match == null){
      break
    }
    matches.push(match)
  }
  return matches
}

// 实现只匹配标签内元素
const regExp = /<div>(.*)<\/div>/g
const res = selectDiv(regExp, str)
console.log(res)

// 2. match 
console.log(str.match(regExp)) // ["<div>1</div>", "<div>2div</div>", "<div>3</div>"]

// 3. replace
function select(regExp, str) {
  let matches = []
  str.replace(regExp, (all, first) => {
    matches.push(first)
  })
  return matches
}

const res2 = select(regExp, str)
console.log(res2)  // ["1", "2div", "3"]

// matchAll
function select2(regExp, str) {
  let matches = []
  for(let match of str.matchAll(regExp)) {
    matches.push(match[1])
  }
  return matches
}

console.log(select2(regExp, str)) // ["1", "2div", "3"]
